package com.bjbn.service.impl;

import com.alibaba.fastjson2.JSON;
import com.bjbn.dto.BmsApiResponse;
import com.bjbn.dto.BmsDeviceValueDto;
import com.bjbn.entity.BmsDeviceGroup;
import com.bjbn.entity.BmsDeviceValue;
import com.bjbn.entity.EqptMapping;
import com.bjbn.mapper.BmsDeviceGroupMapper;
import com.bjbn.mapper.BmsDeviceValueMapper;
import com.bjbn.mapper.EqptMappingMapper;
import com.bjbn.service.BmsApiService;
import com.bjbn.service.ElevatorAlarmService;
import com.bjbn.service.KafkaAlarmPushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ElevatorAlarmServiceImpl implements ElevatorAlarmService {

    @Autowired
    private BmsApiService bmsApiService;
    @Autowired
    private BmsDeviceGroupMapper deviceGroupMapper;
    @Autowired
    private BmsDeviceValueMapper deviceValueMapper;
    @Autowired
    private EqptMappingMapper eqptMappingMapper;
    @Autowired
    private KafkaAlarmPushService kafkaAlarmPushService;

    private static final String ELEVATOR_TYPE = "电梯扶梯";
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void detectAndPushElevatorAlarms() {
        // 1. 查询所有电梯扶梯设备
        List<BmsDeviceGroup> elevatorList = deviceGroupMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<BmsDeviceGroup>()
                        .eq(BmsDeviceGroup::getDeviceType, ELEVATOR_TYPE)
        );
        
        for (BmsDeviceGroup group : elevatorList) {
            String deviceNum = group.getDeviceNum();
            try {
                // 2. 调用BMS API获取实时状态
                BmsApiResponse<BmsDeviceValueDto> response = bmsApiService.getDeviceValueByDeviceId(deviceNum);
                if (response == null || response.getData() == null) {
                    log.warn("获取设备{}实时状态失败", deviceNum);
                    continue;
                }
                
                BmsDeviceValueDto dto = response.getData();
                String deviceValueData = dto.getData();
                
                if (deviceValueData == null) {
                    log.warn("设备{}无数据", deviceNum);
                    continue;
                }
                
                // 3. 更新数据库（保持原有逻辑）
                updateDeviceValueInDatabase(deviceNum, dto);
                
                // 4. 检测故障并推送报警
                Map<String, Object> status = JSON.parseObject(deviceValueData, Map.class);
                if ("1".equals(String.valueOf(status.getOrDefault("故障", "0")))) {
                    // 故障，查资产编码
                    EqptMapping mapping = eqptMappingMapper.selectByBmsCode(deviceNum);
                    if (mapping == null) {
                        log.warn("未找到设备{}的资产映射，无法推送报警", deviceNum);
                        continue;
                    }
                    // 组装报警数据
                    Map<String, Object> alarm = new HashMap<>();
                    alarm.put("assetCode", mapping.getAssetCode());
                    alarm.put("recordTime", sdf.format(new Date()));
                    alarm.put("pushTime", null);
                    alarm.put("alarmValue", "故障");
                    alarm.put("context", deviceValueData);
                    String alarmJson = JSON.toJSONString(alarm);
                    // 推送到Kafka
                    kafkaAlarmPushService.pushAlarm(alarmJson);
                    log.info("电梯扶梯故障报警已推送: {}", alarmJson);
                }
                
                // 避免请求过于频繁
                Thread.sleep(100);
                
            } catch (Exception e) {
                log.error("处理电梯扶梯设备{}异常", deviceNum, e);
            }
        }
    }
    
    /**
     * 更新设备数据到数据库
     */
    private void updateDeviceValueInDatabase(String deviceNum, BmsDeviceValueDto dto) {
        try {
            // 按照device_num为业务主键，插入更新设备采集值表（最新数据）
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<BmsDeviceValue> wrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            wrapper.eq(BmsDeviceValue::getDeviceNum, deviceNum);
            BmsDeviceValue existing = deviceValueMapper.selectOne(wrapper);

            if (existing == null) {
                // 新增
                BmsDeviceValue deviceValue = new BmsDeviceValue();
                deviceValue.setDeviceNum(deviceNum);
                deviceValue.setDeviceValueData(dto.getData());
                deviceValue.setCreateTime(new Date());
                deviceValue.setStatus("1");
                deviceValue.setDelFlag("0");
                deviceValue.setRecordTime(dto.getTime());
                deviceValueMapper.insert(deviceValue);
            } else {
                // 更新
                existing.setDeviceValueData(dto.getData());
                existing.setUpdateTime(new Date());
                existing.setRecordTime(dto.getTime());
                deviceValueMapper.updateById(existing);
            }
            
        } catch (Exception e) {
            log.error("更新设备{}数据到数据库异常", deviceNum, e);
        }
    }
} 